package com.sam.service.impl;

import com.sam.service.IDeepSeekService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

/**
 * AI
 *
 * @author <a href="mailto:807837863.qq.com">sam</a>
 * @since 2025-05-07 16:09
 */
@Service
public class DeepSeekServiceImpl implements IDeepSeekService {

//    @Resource
//    private OpenAiChatModel openAiChatModel;

    @Resource
    private OllamaChatModel ollamaChatModel;


    public DeepSeekServiceImpl(OllamaChatModel ollamaChatModel) {
        this.ollamaChatModel = ollamaChatModel;
    }



//    @Override
//    public String chat(String message) {
//        return openAiChatModel.call(message);
//    }

    @Override
    public Flux<ChatResponse> chatFlux(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return ollamaChatModel.stream(prompt);
    }

    @Override
    public String getResponse(String message) {
        String response = ollamaChatModel.call(message);
        return response;
    }

    @Override
    public SseEmitter sendStreamMessage(String message) {
        SseEmitter emitter = new SseEmitter(60_000L); // 60秒超时

        ollamaChatModel.stream(new Prompt(message))
                .subscribe(
                        chunk -> {
                            try {
                                String content = chunk.getResults().get(0).getOutput().getText();
                                emitter.send(SseEmitter.event().data(content));
                            } catch (IOException e) {
                                emitter.completeWithError(e);
                            }
                        },
                        emitter::completeWithError,
                        emitter::complete
                );

        return emitter;
    }
}
